package cn.jiaqiang.chatgpt.data.trigger.mq;

import cn.jiaqiang.chatgpt.data.types.common.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
@Deprecated
public class RedisInitializer implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onApplicationEvent(@NotNull ContextRefreshedEvent event) {
        // Execute Redis command on application startup
        createQueueIfNotExists(RedisConstants.PAY_SUCCESS_QUEUE_NAME, RedisConstants.PAY_SUCCESS_CONSUMER_GROUP);
    }

    private void createQueueIfNotExists(String key, String group) {
        try {
            // Check if stream exists
            boolean exists = Boolean.TRUE.equals(stringRedisTemplate.hasKey(key));

            if (!exists) {
                // If stream does not exist, create it
                stringRedisTemplate.opsForStream().createGroup(key, group);
                log.info("Queue {} and group {} created successfully.", key, group);
            } else {
                log.info("Queue {} and group {} already exists.", key, group);
            }
        } catch (Exception ex) {
            log.error("Error creating queue: {}", ex.getMessage());
        }
    }
}